package com.woniu.config;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.woniu.util.JwtTokenUtil;
import com.woniu.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

@Component
public class MyAuthenticationSuccessHandler  implements AuthenticationSuccessHandler {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        String username = request.getParameter("username");
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        String s = authorities.toString();
        ValueOperations ops = redisTemplate.opsForValue();
        ops.set(username,authorities);
//        生成token返回给前端，同时我们可以把该用户的权限标识符查询出来存redis
        String token = null;
        try {
            token = JwtTokenUtil.createSign(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResponseResult<String> success = new ResponseResult<>(token,"登录成功",200);
        response.setContentType("application/json;charset=utf-8");
//        ResponseResult<String> success = ResponseResult.ok();
//        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(new ObjectMapper().writeValueAsString(success));
        out.flush();
        out.close();
    }
}